package com.smartbone.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Encryption {

	private static final String TYPE_32 = "TYPE_32";
	
	private static final String TYPE_16 = "TYPE_16";
	
	private static String encrypt(String plainText, String type) {
		StringBuffer buf = new StringBuffer("");
		
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes());
			byte b[] = md.digest();

			int i;


			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}

		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if (TYPE_32.equals(type)) {
			return buf.toString();
		} else {
			return buf.toString().substring(8, 24);
		}
	}

	public static String encrypt32(String plainText){
		return encrypt(plainText, TYPE_32);
	}
	
	public static String encrypt16(String plainText){
		return encrypt(plainText, TYPE_16);
	}

}
